<template>
  <div class="main-content">
    <div style="width: 70%; background-color: white; margin: 30px auto; border-radius: 20px">
      <div style="padding-bottom: 10px">
        <div style="display: flex; font-size: 18px; color: #000000FF; line-height: 80px; border-bottom: #cccccc 1px solid;">
          <div style="margin-left: 20px; flex: 1">全部商品（{{ goodsData.length }}件）</div>
          <div style="flex: 2; text-align: right">
            <el-select v-model="addressId" placeholder="请选择收货地址" style="width: 70%">
              <el-option v-for="item in addressData" :label="item.username + ' - ' + item.userAddress + ' - ' + item.phone" :value="item.id"></el-option>
            </el-select>
          </div>
          <div style="flex: 1; font-size: 16px; text-align: right; padding-right: 20px">
            已选商品 ￥ {{totalPrice}} <el-button type="danger" round @click="pay">下单</el-button>
          </div>
        </div>
        <div style="margin: 20px 0; padding: 0 50px">
          <div class="table">
            <el-table :data="goodsData" strip @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column label="商品图片" width="120px">
                <template v-slot="scope">
                  <el-image style="width: 80px; height: 60px; border-radius: 3px" v-if="scope.row.goodsImg"
                            :src="scope.row.goodsImg" :preview-src-list="[scope.row.goodsImg]"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品名称" width="240px">
                <template v-slot="scope">
                  <a @click="$router.push('/front/detail?id=' + scope.row.goodsId)">{{scope.row.goodsName}}</a>
                </template>
              </el-table-column>
              <el-table-column prop="businessName" label="店铺名称">
                <template v-slot="scope">
                  <a  @click="$router.push('/front/business?id=' + scope.row.businessId)">{{scope.row.businessName}}</a>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="商品价格"></el-table-column>
              <el-table-column prop="num" label="选择数量">
                <template v-slot="scope">
                  <el-input-number v-model="scope.row.num" style="width: 100px" @change="handleChange(scope.row)" :min="1"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180">
                <template v-slot="scope">
                  <el-button size="mini" type="danger" plain @click="del(scope.row.id)">移除购物车</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination" style="margin-top: 20px">
              <el-pagination
                  background
                  @current-change="handleCurrentChange"
                  :current-page="current"
                  :page-sizes="[5, 10, 20]"
                  :page-size="pageSize"
                  layout="total, prev, pager, next"
                  :total="total">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      goodsData: [],
      current: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      totalPrice: 0,
      total: 0,
      addressId: null,
      addressData: [],
      selectedData: [],
      ordersAddRequests:[],
      cartId:0
    }
  },
  mounted() {
    this.loadGoods(1)
    this.loadAddress()
  },
  // methods：本页面所有的点击事件或者其他函数定义区
  methods: {
    loadAddress() {
      this.$request.get('/address/selectAll').then(res => {
        console.log(res)
        if (res.code === 0) {
          this.addressData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    loadGoods(current) {
      if (current) this.current = current
      this.$request.post('/cart/selectPage', {

          current: this.current,
          pageSize: this.pageSize,

      }).then(res => {
        if (res.code === 0) {
          this.goodsData = res.data?.records
          this.total =Number(res.data?.total)
          this.goodsId = res.data?.records.goodsId
          this.businessId = res.data?.records.businessId
          this.businessName = res.data?.records.businessName
        } else {
          this.$message.error(res.message)
        }
      })
    },

    del(id) {
      this.$request.delete('/cart/delete/' + id).then(res => {
        console.log(id)
        if (res.code === 0) {
          this.$message.success('移除成功')
          this.loadGoods(1)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleCurrentChange(current) {
      this.loadGoods(current)
    },
    handleSelectionChange(rows) {
      this.totalPrice = 0
      this.selectedData = rows
      // 计计算总价格
      this.selectedData.forEach(item => {
        this.totalPrice += (item.price * item.num)
      })
    },
    handleChange(row) {
      this.totalPrice = 0
      this.selectedData.forEach(item => {
        this.totalPrice += item.price * item.num
      })
    },
    pay() {
      const rows = this.selectedData; // 这里的this.tableData应该是你的表格数据源


      // 清空现有数组
      this.ordersAddRequests.splice(0, this.ordersAddRequests.length);

      // 遍历rows数组
      rows.forEach(row => {
        // 创建一个新对象，包含addressId和row中的数据
        const newRow = {
          addressId: this.addressId,
          businessId: row.businessId,
          goodsId: row.goodsId,
          num: row.num,
          cartId:row.id
        };

        // 将新对象添加到array中
        this.ordersAddRequests.push(newRow);
      });

      if (!this.addressId) {
        this.$message.warning('请选择收货地址')
        return
      }
      if (!this.ordersAddRequests || this.ordersAddRequests.length === 0) {
        this.$message.warning('请选择商品')
        return
      }
      let data = {
        //userId: this.userId,
       // addressId: this.addressId,
        ordersAddRequests:
            {
            addressId: this.ordersAddRequests.addressId,
            businessId: this.ordersAddRequests.businessId,
            goodsId: this.ordersAddRequests.goodsId,
            num: this.ordersAddRequests.num,
              cartId:this.ordersAddRequests.cartId
          }
      }
      this.$request.post('/orders/add', this.ordersAddRequests).then(res => {
        console.log(this.ordersAddRequests)
        console.log(res)
        if (res.code === 0) {
          this.$message.success('操作成功')
          this.loadGoods(1)
        } else {
          this.$message.error(res.message)
        }
      })
    },





  }
}
</script>


data() {
return {
array: [] // 用来存储添加的对象
};
},
methods: {
populateArray() {
// 假设你有一个rows数组，包含了所有的行数据
const rows = this.tableData; // 这里的this.tableData应该是你的表格数据源

// 定义addressId
const addressId = 1;

// 清空现有数组
this.array.splice(0, this.array.length);

// 遍历rows数组
rows.forEach(row => {
// 创建一个新对象，包含addressId和row中的数据
const newRow = {
addressId: addressId,
businessId: row.businessId,
goodsId: row.goodsId,
num: row.num
};

// 将新对象添加到array中
this.array.push(newRow);
});

// 打印array查看结果
console.log(this.array);
}
}
